package controllers

import (
	"findme-api/models"
	"fmt"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"github.com/garyburd/redigo/redis"
	//"strconv"

	//"reflect"
	//"strings"
)

type AlarmController struct {
	beego.Controller
}
//告警结构体
type Data struct {
	Id  string `json:"id"`
	Deviceid string `json:"deviceid"`
	Type string `json:"type"`
	Alarmtype string `json:"alarmtype"`
	CompanyName string `json:"company_name"`
	Date string `json:"date"`
}

//返回数据json格式
type AJSONS struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	DATA []Data  `json:"data"`
}


//func (c *AlarmController) AlarmAllowCross() {
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")    //允许访问类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
//	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
//}




//读取所有人员告警
func (this *AlarmController) ReadpeopleAlarm() {
	FileLogs.Info("===读取所有人员告警===")
	//this.AlarmAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	page := this.GetString("page")
	size := this.GetString("size")
    jsoninfo := ParseToken(token)
    username := Getusernamefromjsoninfo(jsoninfo)
    company := models.QueryCompanyByUsername(username)
	//fmt.Println(username)
	//var allslice = []string{}
	alarmDataChan := make(chan string, 100000)
	totalItem := models.ReadAlarm(alarmDataChan,company,page,size,"1")
	alarmdata := []Data{}
	tempdata := Data{"","","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenalarmchan = len(alarmDataChan)
	if lenalarmchan != 0 {
		for item := range alarmDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = Data{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5]}
			alarmdata = append(alarmdata, tempdata)
			if i == (lenalarmchan - 1) {
				break
			}
			i++
		}
		data := &AJSONS{0,totalItem,alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		alarmdata = append(alarmdata, tempdata)
		data := &AJSONS{1, totalItem, alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//读取所有设备告警
func (this *AlarmController) ReadequipmentAlarm() {
	//this.AlarmAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	page := this.GetString("page")
	size := this.GetString("size")
	jsoninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(jsoninfo)
	company := models.QueryCompanyByUsername(username)
	alarmDataChan := make(chan string, 100000)
	totalItem := models.ReadAlarm(alarmDataChan,company,page,size,"2")
	alarmdata := []Data{}
	tempdata := Data{"","","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenalarmchan = len(alarmDataChan)
	if lenalarmchan != 0 {
		for item := range alarmDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = Data{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5]}
			alarmdata = append(alarmdata, tempdata)
			if i == (lenalarmchan - 1) {
				break
			}
			i++
		}
		data := &AJSONS{0,totalItem,alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		alarmdata = append(alarmdata, tempdata)
		data := &AJSONS{1, totalItem, alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}
}

//条件查询告警记录
func (this *AlarmController)Queryalarm(){
	FileLogs.Info("===条件查询告警记录===")
	//this.AlarmAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	starttime := this.GetString("starttime")
	endtime := this.GetString("endtime")
	alarmtype := this.GetString("alarmtype")
	page := this.GetString("page")
	size := this.GetString("size")
	deviceid := this.GetString("deviceid")
	jsoninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(jsoninfo)
	company := models.QueryCompanyByUsername(username)
	alarmDataChan := make(chan string, 100000)
	totalItem := models.Queryalarmbycondition(alarmDataChan,company,starttime,endtime,alarmtype,deviceid,page,size)
	//fmt.Println(totalItem)
	alarmdata := []Data{}
	tempdata := Data{"","","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenalarmchan = len(alarmDataChan)
	if lenalarmchan != 0 {
		for item := range alarmDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = Data{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5]}
			alarmdata = append(alarmdata, tempdata)
			if i == (lenalarmchan - 1) {
				break
			}
			i++
		}
		data := &AJSONS{0,totalItem,alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		alarmdata = append(alarmdata, tempdata)
		data := &AJSONS{1, totalItem, alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}
}



//搜索告警记录,该接口暂时不调用
func (this *AlarmController) SearchAlarm() {
	//this.AlarmAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	page := this.GetString("page")
	size := this.GetString("size")
    pageint,_ := strconv.Atoi(page)
	sizeint, _ := strconv.Atoi(size)
	searchstring := this.GetString("searchstring")
	querylittletype := this.GetString("querylittletype")
	jsoninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(jsoninfo)
	slice := []uint64{}
	//建立索引，并返回搜索到的数据在索引中的位置
	Search(searchstring,&slice,username,"alarm",querylittletype)
	FileLogs.Info("======搜到的数据在索引中的位置======",slice)
	alarmDataChan := make(chan string, 100000)
	totalItem := models.SearchAlarm(alarmDataChan,username,querylittletype)
	//fmt.Println(totalItem)
	alarmdata := []Data{}
	tempdata := Data{"","","","","",""}
	//遍历信道，读取数据
	var i int = 1//索引计数
	var j int = 1 //用于返回分页
	var lenalarmchan = len(alarmDataChan)
	if lenalarmchan != 0 {
		for item := range alarmDataChan{
			for _,v := range slice {
				if i == int(v) {
					if j > (pageint-1)*sizeint  && j <= pageint*sizeint {
						//fmt.Println("get data from database:",item)
						//m[strconv.Itoa(i)] =item
						itemsegments := strings.Split(item, "and")
						tempdata = Data{itemsegments[0], itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5]}
						alarmdata = append(alarmdata, tempdata)
					}
					j++
				}
			}
			if i == (lenalarmchan - 1) {
				break
			}
			i++
		}
		data := &AJSONS{0,totalItem,alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		alarmdata = append(alarmdata, tempdata)
		data := &AJSONS{1, totalItem, alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//前端收到告警信息或者取消告警信息后，修改redis中是否已收到的标志位
func (this *AlarmController) Resettoredis() {
	fmt.Println("====前端已经收到告警====")
	token := this.Ctx.Request.Header.Get("Authorization")
	fmt.Println(token)
	labelid := this.GetString("labelid")
	confirmtype := this.GetString("confirmtype")

	fmt.Println(confirmtype)
	//conn,err := redis.Dial("tcp","47.105.190.126:6379")
	conn,err := redis.Dial("tcp","192.168.1.109:6379")
	if err != nil {
		fmt.Println("connect redis error :",err)
		return
	}
	isExist, err := conn.Do("hexists",labelid,confirmtype)
	if err != nil {
		fmt.Println("err while checking keys:", err)
	}
	if isExist.(int64) == 1 {
		if confirmtype == "alarm" {
			fmt.Println("收到前端回应，设置redis为已收到")
			_, err = conn.Do("HSET", labelid, confirmtype, "Received")
			if err != nil {
				fmt.Println("redis set error:", err)
			}
		}else if confirmtype == "cancel" {
			_, err = conn.Do("HSET", labelid, confirmtype, "Received")
			if err != nil {
				fmt.Println("redis set error:", err)
			}
		}
	}
	this.Ctx.WriteString("已收到信息")
}







